package com.dtjd.playcoinmonkey.activities.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dtjd.playcoinmonkey.BuildConfig;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.activities.AccountActivity;
import com.dtjd.playcoinmonkey.activities.AdminActivity;
import com.dtjd.playcoinmonkey.activities.LoginActivity;
import com.dtjd.playcoinmonkey.activities.MyCollectionActivity;
import com.dtjd.playcoinmonkey.activities.MyPostActivity;
import com.dtjd.playcoinmonkey.activities.PolicyActivity;
import com.dtjd.playcoinmonkey.adapter.MeListAdapter;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.bean.MeListBean;
import com.dtjd.playcoinmonkey.bean.UserBean;
import com.dtjd.playcoinmonkey.databinding.DialogDownBinding;
import com.dtjd.playcoinmonkey.databinding.FragmentMeBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MeFragment extends Fragment {
    private FragmentMeBinding binding;
    private MeListAdapter adp;
    private final List<MeListBean> data=new ArrayList<>();
    private MainActivity activity;
    private ActivityResultLauncher<Intent> launcher;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMeBinding.inflate(inflater, container, false);
        activity= (MainActivity) requireActivity();
        adp=new MeListAdapter(activity,data);
        binding.meList.setAdapter(adp);
        binding.meList.setOnItemClickListener((adapterView, view, i, l) -> {
            MeListBean bean = data.get(i);
            if (bean.cmd.equals("exit")){
                String token=MyApplication.sp.getString("token","null");
                if (token.equals("null")){
                    startActivity(new Intent(activity, LoginActivity.class));
                    SharedPreferences.Editor edit = MyApplication.sp.edit();
                    edit.putString("token","");
                    edit.apply();
                    activity.finish();
                }else{
                    ArrayList<HttpParaBean> list = new ArrayList<>();
                    list.add(new HttpParaBean("token","token"));
                    Network.post(list, "wbh/logout", new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); }
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            activity.runOnUiThread(() -> {
                                try {
                                    JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string());
                                    if (jo.getInt("code") == 2){
                                        SharedPreferences.Editor edit = MyApplication.sp.edit();
                                        edit.putString("token","");
                                        edit.apply();
                                        startActivity(new Intent(activity, LoginActivity.class));
                                        activity.finish();
                                    }else{
                                        Tools.toast( jo.getString("datalist"));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                }
            }
            if (bean.cmd.equals("accountmsg")){
                launcher.launch(new Intent(activity, AccountActivity.class), ActivityOptionsCompat.makeSceneTransitionAnimation(activity, binding.meIcon, "icon"));
            }
            if (bean.cmd.equals("privatepolicy")){
                Intent intent=new Intent(activity, PolicyActivity.class);
                intent.putExtra("type","Privacy");
                startActivity(intent);
            }
            if (bean.cmd.equals("serviceitem")){
                Intent intent=new Intent(activity, PolicyActivity.class);
                intent.putExtra("type","Service");
                startActivity(intent);
            }
            if (bean.cmd.equals("admin")){
                startActivity(new Intent(activity, AdminActivity.class));
            }
            if (bean.cmd.equals("update")){
                Network.post(new ArrayList<>(), "wbhMain/getVersion", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @SuppressLint("UseCompatLoadingForDrawables")
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        activity.runOnUiThread(() -> {
                            try {
                                JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string()).getJSONObject("datalist");
                                String url = jo.getString("url");

                                if (jo.getInt("version")>activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode){
                                    BottomSheetDialog dialog = new BottomSheetDialog(activity);
                                    @SuppressLint("InflateParams") View commentView = LayoutInflater.from(activity).inflate(R.layout.dialog,null);
                                    ((TextView)commentView.findViewById(R.id.dialog_title)).setText(getString(R.string.newVersionFOund));
                                    ((TextView)commentView.findViewById(R.id.dialog_content)).setText(getString(R.string.newVersionIs,jo.getString("versionName")));
                                    TextView left=commentView.findViewById(R.id.dialog_button_left);
                                    TextView right=commentView.findViewById(R.id.dialog_button_right);
                                    left.setText(getResources().getString(R.string.update));
                                    right.setText(getResources().getString(R.string.cancel));
                                    left.setOnClickListener(view->{
                                        downloadNewVersion(url);
                                        dialog.dismiss();
                                    });
                                    right.setOnClickListener(view-> dialog.dismiss());
                                    dialog.setCancelable(false);
                                    dialog.setContentView(commentView);
                                    dialog.show();
                                }else{
                                    Tools.toast( getString(R.string.have_been_latest_version));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        });
        binding.myAccountDetail.setOnClickListener(view -> launcher.launch(new Intent(activity, AccountActivity.class), ActivityOptionsCompat.makeSceneTransitionAnimation(activity, binding.meIcon, "icon")));
        binding.meMyCollect.setOnClickListener(view -> startActivity(new Intent(activity, MyCollectionActivity.class)));
        binding.meMyPosts.setOnClickListener(view -> startActivity(new Intent(activity, MyPostActivity.class)));
        refresh();
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> refresh());
        return binding.getRoot();
    }
    @SuppressLint("SetTextI18n")
    private void downloadNewVersion(String url) {
        @NonNull DialogDownBinding dbinding = DialogDownBinding.inflate(activity.getLayoutInflater());
        AlertDialog dialog1=new AlertDialog.Builder(activity).setView(dbinding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog1.getWindow().getAttributes();
        p.width = ((int)(activity.getWindowManager().getDefaultDisplay().getWidth() * 0.8));
        dialog1.getWindow().setAttributes(p);
        dialog1.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.dialogbg,null));
        dialog1.setView(dbinding.getRoot());
        dialog1.show();

        FileDownloader.setup(activity);
        FileDownloader.getImpl().create(url).setPath(FileDownloadUtils.getDefaultSaveRootPath()+File.separator+"1.apk").setListener(new FileDownloadListener() {

            @Override
            protected void pending(BaseDownloadTask task, int progress, int totalBytes) {
                dbinding.progressbar.setMax(totalBytes);
                dbinding.progressbar.setProgress(progress);
                dbinding.text.setText("Pending...");
            }
            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int progress, int totalBytes) {
                dbinding.progressbar.setMax(totalBytes);
                dbinding.progressbar.setProgress(progress);
                dbinding.text.setText("Pending...");
            }

            @Override
            protected void progress(BaseDownloadTask task, int progress, int totalBytes){
                dbinding.progressbar.setMax(totalBytes);
                dbinding.progressbar.setProgress(progress);
                dbinding.text.setText(Tools.getPercent(progress,totalBytes));

            }
            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }
            @Override
            protected void retry(final BaseDownloadTask errortask, final Throwable ex, final int retryingTimes, final int progress) {
                dbinding.progressbar.setProgress(progress);
                dbinding.text.setText("正在重试");
            }
            @Override
            protected void completed(BaseDownloadTask task) {
                dbinding.text.setText("正在安装");
                File file = new File(FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "1.apk");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".FileProvider", file);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                startActivity(intent);
            }
            @Override
            protected void paused(BaseDownloadTask task, int progress, int totalBytes) {
                dbinding.progressbar.setMax(totalBytes);
                dbinding.progressbar.setProgress(progress);
                dbinding.text.setText(Tools.getPercent(progress,totalBytes));
            }
            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                e.printStackTrace();
            }
            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();

    }
    private void addListItem(boolean showAdmin, String versionName,boolean isUpdate) {
        data.clear();
        data.add(new MeListBean(R.drawable.exit,"","",true,"",0,false));
        data.add(new MeListBean(R.drawable.accountmsg,getResources().getString(R.string.accountmsg),getResources().getString(R.string.update_account_msg),true,"accountmsg",1,false));
        data.add(new MeListBean(R.drawable.exit,"","",false,"",0,false));
        data.add(new MeListBean(R.drawable.privatepolicy,getResources().getString(R.string.privacyPolicy_noBook),"",true,"privatepolicy",1,false));
        data.add(new MeListBean(R.drawable.serviceitem,getResources().getString(R.string.serviceItems_noBook),"",true,"serviceitem",1,false));
        data.add(new MeListBean(R.drawable.update, getResources().getString(R.string.version_update),"2.0.2", true, "update", 1,isUpdate));
        if(showAdmin)data.add(new MeListBean(R.drawable.admin,getResources().getString(R.string.admin_entrance),"",true,"admin",1,false));
        data.add(new MeListBean(R.drawable.exit,"","",true,"",0,false));
        data.add(new MeListBean(R.drawable.exit,getResources().getString(R.string.logout),getResources().getString(R.string.relogin),true,"exit",1,false));
        adp.notifyDataSetChanged();
    }
    private void refresh() {
        ArrayList<HttpParaBean> list=new ArrayList<>();
        list.add(new HttpParaBean("token", "token"));
        Network.post(list, "wbh/userInfo", new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        String str= Objects.requireNonNull(response.body()).string();
                        JSONObject jo = new JSONObject(str);
                        if (jo.getInt("code")==2726297){
                            startActivity(new Intent(activity, LoginActivity.class));
                            Tools.toast( jo.getString("datalist"));
                        }else {
                            JSONObject jo1 = jo.getJSONArray("datalist").getJSONObject(0);
                            MyApplication.user=new UserBean(jo1.getString("wu_name"),jo1.getString("wb_post_count"), jo1.getString("wb_collection_count"), jo1.getString("wb_nickname"), jo1.getString("wb_url"));
                            Glide.with(activity).load(MyApplication.user.wb_url).apply(RequestOptions.bitmapTransform(new CircleCrop())).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.meIcon);
                            if (MyApplication.user!=null){
                                binding.meMail.setText(MyApplication.user.wu_name);
                                binding.meNickname.setText(MyApplication.user.wb_nickname);
                                binding.mePostNum.setText(String.valueOf(MyApplication.user.wb_post_count));
                                binding.meCollectNum.setText(String.valueOf(MyApplication.user.wb_collection_count));
                            }
                            Network.post(new ArrayList<>(), "wbhMain/getVersion", new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    e.printStackTrace();
                                }
                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) {
                                    activity.runOnUiThread(() -> {
                                        try {
                                            JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject().getAsJsonObject("datalist");
                                            if (jo.get("version").getAsInt()>activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode){
                                                addListItem((jo1.getInt("is_admin")==1),jo.get("versionName").getAsString(),true);
                                                if (jo.get("forcedUpdate").getAsString().equals("1")){
                                                    BottomSheetDialog dialog = new BottomSheetDialog(activity);
                                                    @SuppressLint("InflateParams") View commentView = LayoutInflater.from(activity).inflate(R.layout.dialog,null);
                                                    ((TextView)commentView.findViewById(R.id.dialog_title)).setText(getString(R.string.newVersionFOund));
                                                    ((TextView)commentView.findViewById(R.id.dialog_content)).setText(getString(R.string.newVersionIs,jo.get("versionName").getAsString()));
                                                    TextView left=commentView.findViewById(R.id.dialog_button_left);
                                                    TextView right=commentView.findViewById(R.id.dialog_button_right);
                                                    left.setText(getResources().getString(R.string.update));
                                                    right.setText(getResources().getString(R.string.exit));
                                                    left.setOnClickListener(view->{
                                                        Intent intent=new Intent();
                                                        intent.setAction(Intent.ACTION_VIEW);
                                                        intent.setData(Uri.parse("https://www.m2.app/"));
                                                        startActivity(intent);
                                                    });
                                                    right.setOnClickListener(view-> activity.finish());
                                                    dialog.setCancelable(false);
                                                    dialog.setContentView(commentView);
                                                    dialog.show();
                                                }
                                            }else{
                                                addListItem((jo1.getInt("is_admin")==1),jo.get("versionName").getAsString(),false);
                                            }
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            });
                        }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                });
            }
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}